package spider.netty.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Set;

/**
 * RedisManager
 *
 * @author Archx[archx@foxmail.com]
 * @date 2017/4/8.
 */
public class RedisManager {

    private static final Logger logger = LoggerFactory.getLogger(RedisManager.class);

    private String host; // 地址
    private int port; // 端口
    private String password; // 密码
    private int timeout = 3600; // 超时
    private String nodeId; // 节点

    private JedisPool jedisPool;

    public void set(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        jedis.set(key, value);
        jedis.close();
    }

    public String get(String key) {
        Jedis jedis = jedisPool.getResource();
        String value = jedis.get(key);
        jedis.close();
        return value;
    }

    public void remove(String key) {
        Jedis jedis = jedisPool.getResource();
        jedis.del(key);
        jedis.close();
    }

    @PostConstruct
    public void init() {
        logger.info("> Redis initialize");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setMaxIdle(300);
        config.setMinIdle(2);
        config.setMaxTotal(300);
        jedisPool = new JedisPool(config, host, port, timeout, password);

        Jedis jedis = jedisPool.getResource();
        if (jedis != null) {
            Set<String> keys = jedis.keys("*");
            for (String key : keys) {
                if (jedis.get(key).equals(nodeId)) {
                    jedis.del(key);
                }
            }
        }
        jedis.close();
        logger.info("> Redis connected");
    }

    @PreDestroy
    public void close() {
        if (jedisPool != null)
            jedisPool.close();
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setNodeId(String nodeId) {
        this.nodeId = nodeId;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}
